import React from 'react';
import { Input, Select } from 'antd';
import { isEqual } from 'lodash';
import PropTypes from 'prop-types';

const InputGroup = Input.Group;
const { Search } = Input;
const { Option } = Select;

class SelectField extends React.Component {
  static propTypes = {
    options: PropTypes.array, // 下拉框选项值
    hasSearchBtn: PropTypes.bool, // 是否带有搜索按钮
    onSearch: PropTypes.func, // 搜索回调钩子
    onChange: PropTypes.func, // 值变化回调钩子
    onPressEnter: PropTypes.func, // enter事件钩子
  };

  static defaultProps = {
    options: [],
    hasSearchBtn: false,
    onSearch: () => {},
    onChange: () => {},
    onPressEnter: () => {},
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    const { value = {} } = nextProps;
    if (!isEqual(value, { key: prevState.key, value: prevState.value })) {
      return {
        key: value.key,
        value: value.value,
      };
    }
    return null;
  }

  state = {
    key: undefined,
    value: undefined,
  };

  // 下拉框选择变动
  onSelectChange = value => {
    this.setState({
      key: value,
    });
    const { onChange } = this.props;
    const params = { key: value, value: this.state.value };
    onChange(params);
  };

  // 输入框输入
  onInputChange = e => {
    this.setState({
      value: e.target.value,
    });
    const { onChange } = this.props;
    const params = { key: this.state.key, value: e.target.value };
    onChange(params);
  };

  render() {
    const { options = [], hasSearchBtn = false, onSearch, onPressEnter } = this.props;
    const { key, value } = this.state;
    return (
      <div>
        <InputGroup compact>
          <Select value={key} onChange={this.onSelectChange} style={{ width: '35%' }}>
            {options.map(item => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
          {hasSearchBtn ? (
            <Search
              onSearch={v => onSearch({ [key]: v })}
              style={{ width: '65%' }}
              onChange={this.onInputChange}
              value={value}
              onPressEnter={onPressEnter}
            />
          ) : (
            <Input
              style={{ width: '65%' }}
              onChange={this.onInputChange}
              value={value}
              onPressEnter={onPressEnter}
            />
          )}
        </InputGroup>
      </div>
    );
  }
}

export default SelectField;
